﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace DatabaseBackup.Library
{
    public class DifferentialBackup
    {
        public static void PerformDifferentialBackup()
        {
            try
            {
                using (SqlConnection con = new SqlConnection(Helpers.ConnectionString))
                {
                    string[] databases = Helpers.Databases;

                    for (int i = 0; i < databases.Count(); i++)
                    {
                        string fileName = string.Format("D-{0}{1:yyyyMMddHHmm}", databases[i], DateTime.UtcNow);

                        StringBuilder query = new StringBuilder();

                        query.Append("BACKUP DATABASE " + databases[i]);
                        query.Append(string.Format(@" TO DISK = '{0}{1}' WITH DIFFERENTIAL", Helpers.BackupFolder, fileName + ".bak"));

                        SqlCommand cmd = new SqlCommand(query.ToString(), con);

                        con.Open();
                        cmd.ExecuteNonQuery();

                        if (Helpers.FTPEnabled)
                            AmazonS3Handler.TransferFile(Helpers.BackupFolder + fileName + ".bak");
                    }
                }

                FileHistoryCleanup.CleanOldFiles(FileType.DifferentialBackup);
            }
            catch (Exception ex)
            {
                ErrorHandler.AddToErrorLog(ex, BackupType.Differential);
            }
        }
    }
}
